package com.errol.batchprocessor.payroll.advisorimpl.common.multiemployeeinbatch;

import com.renjia.constant.Constant;
import com.renjia.enums.SwitchEnum;
import com.renjia.properties.SpecialCustomerProperties;
import com.renjia.service.generic.log.LogService;
import com.renjia.service.generic.support.payroll.PayrollAmountSupportService;
import com.renjia.service.module.employeeaddition.advisorimpl.EmployeeAdvisorTypeEnum;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeeBatchPayload;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeePiecePayload;
import com.renjia.service.module.employeeaddition.advisorimpl.payroll.payload.PayrollEmployeeSinglePayload;
import com.renjia.service.module.payroll.advisor.verify.PayrollVerifySingleProcessAdvisor;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 发放批次不校验人员重复扩展
 */

@Service
public class PayLimitImportAdvisorImpl implements PayrollVerifySingleProcessAdvisor {
    private final PayrollAmountSupportService payrollAmountSupportService;
    private final SpecialCustomerProperties specialCustomerProperties;
    private final LogService logService;

    public PayLimitImportAdvisorImpl(PayrollAmountSupportService payrollAmountSupportService,
                                     SpecialCustomerProperties specialCustomerProperties,
                                     LogService logService) {
        this.payrollAmountSupportService = payrollAmountSupportService;
        this.specialCustomerProperties = specialCustomerProperties;
        this.logService = logService;
    }

    @Override
    public boolean shallProcess(@NonNull PayrollEmployeeBatchPayload advisorPayload) {
        return EmployeeAdvisorTypeEnum.PAYROLL_RECORD == advisorPayload.getAdvisorTypeEnum()
                && SwitchEnum.OFF.getCode2().equals(advisorPayload.getCoreCustomerChannelMerchant().getAllowEmployeeRepeat());
    }

    @Override
    public int priority() {
        return 112;
    }

    @Override
    public boolean doExecuteOnEmployeeInfoSavedAtVerifyStage(PayrollEmployeeSinglePayload singlePayload, PayrollEmployeePiecePayload piecePayload, PayrollEmployeeBatchPayload batchPayload) {
        //5.2.0添加服务费小于0的过滤
        if (singlePayload.getSingleEntity().getShouldPayBrokerage().compareTo(BigDecimal.ZERO) < Constant.COMMON_ZERO) {
            singlePayload.getErrMsgList().add("服务费不能小于0");
            return false;
        }
        BigDecimal inFactPayAmount = getInFactPayAmount(singlePayload, piecePayload, batchPayload);
        BigDecimal monthlyUsedAmount = payrollAmountSupportService.getMonthlyUsedAmountOfEmployee(singlePayload.getCoreEmployee().getId(),
                singlePayload.getSingleEntity().getPayTime());
        BigDecimal allBatchAmount = null;
        boolean off = false;
        synchronized (this) {
            BigDecimal sum = batchPayload.getMap().get(singlePayload.getDocumentNumber());
            if (sum != null) {
                allBatchAmount = monthlyUsedAmount.add(sum);
            } else {
                allBatchAmount = monthlyUsedAmount;
            }
            if (allBatchAmount.add(inFactPayAmount).compareTo(batchPayload.getPayLimitPayload().getMonthLimitAmount()) > 0) {
                off = true;
            } else {
                if (sum != null) {
                    batchPayload.getMap().put(singlePayload.getDocumentNumber(), batchPayload.getMap().get(singlePayload.getDocumentNumber()).add(inFactPayAmount));
                } else {
                    batchPayload.getMap().put(singlePayload.getDocumentNumber(), inFactPayAmount);
                }
            }
        }
        if (off) {
            singlePayload.getErrMsgList().add(String.format("当月最高限额：￥%s, 当月已发放：￥%s（不含当次）", batchPayload.getPayLimitPayload().getMonthLimitAmount(), monthlyUsedAmount));
            return false;
        } else {
            logService.debug("【人员导入批处理】【" + batchPayload.getBatchEntity().getBatchNo() + "】【" + singlePayload.getSingleEntity().getId() + "】月限额验证通过");
        }
        return true;
    }

    protected BigDecimal getInFactPayAmount(PayrollEmployeeSinglePayload singlePayload, PayrollEmployeePiecePayload piecePayload, PayrollEmployeeBatchPayload batchPayload) {
        // 人员信息验证通过后，检查月限额
        // 本次发放金额
        BigDecimal inFactPayAmount = singlePayload.getSingleEntity().getInfactPayAmount();
        // 服务费
        BigDecimal managerFree = singlePayload.getSingleEntity().getInfactPayAmount().multiply(batchPayload.getCoreCustomerChannelMerchant().getManageRate()).setScale(2,
                RoundingMode.HALF_UP);
        if (batchPayload.getCoreCustomerChannelMerchant().getCustomerId().equals(specialCustomerProperties.getSsbAppId())) {
            // 省省吧客户服务费
            BigDecimal customerManagerFree = singlePayload.getSingleEntity().getInfactPayAmount().multiply(new BigDecimal("0.015")).setScale(2, RoundingMode.HALF_UP);
            //应发总额
            inFactPayAmount = singlePayload.getSingleEntity().getInfactPayAmount().subtract(managerFree).subtract(customerManagerFree).setScale(2, RoundingMode.HALF_UP);
        }
        return inFactPayAmount;
    }
}
